using System;
using System.Windows.Forms;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 窗体控件辅助类
    /// 用于在Designer未定义控件时，通过名称查找控件
    /// </summary>
    public static class FormControlHelper
    {
        /// <summary>
        /// 获取控件文本值
        /// </summary>
        public static string GetControlText(Control parent, string controlName)
        {
            var controls = parent.Controls.Find(controlName, true);
            if (controls.Length > 0)
            {
                if (controls[0] is TextBox textBox)
                    return textBox.Text ?? "";
                if (controls[0] is ComboBox comboBox)
                    return comboBox.Text ?? "";
                if (controls[0] is Label label)
                    return label.Text ?? "";
            }
            return "";
        }

        /// <summary>
        /// 设置控件文本值
        /// </summary>
        public static void SetControlText(Control parent, string controlName, string value)
        {
            var controls = parent.Controls.Find(controlName, true);
            if (controls.Length > 0)
            {
                if (controls[0] is TextBox textBox)
                    textBox.Text = value;
                if (controls[0] is ComboBox comboBox)
                    comboBox.Text = value;
                if (controls[0] is Label label)
                    label.Text = value;
            }
        }

        /// <summary>
        /// 获取控件值（用于DateTimePicker等）
        /// </summary>
        public static DateTime? GetControlDateTime(Control parent, string controlName)
        {
            var controls = parent.Controls.Find(controlName, true);
            if (controls.Length > 0 && controls[0] is DateTimePicker dateTimePicker)
            {
                return dateTimePicker.Value;
            }
            return null;
        }

        /// <summary>
        /// 设置控件日期时间值
        /// </summary>
        public static void SetControlDateTime(Control parent, string controlName, DateTime value)
        {
            var controls = parent.Controls.Find(controlName, true);
            if (controls.Length > 0 && controls[0] is DateTimePicker dateTimePicker)
            {
                dateTimePicker.Value = value;
            }
        }

        /// <summary>
        /// 获取控件（通用方法）
        /// </summary>
        public static T? GetControl<T>(Control parent, string controlName) where T : Control
        {
            var controls = parent.Controls.Find(controlName, true);
            if (controls.Length > 0 && controls[0] is T control)
            {
                return control;
            }
            return null;
        }
    }
}

